package com.shadow.quartz;

import com.shadow.common.exception.RException;
import com.shadow.common.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * 根据任务配置反射转到任务执行入口.
 * @author: Pbody
 * @date: 2021/3/23 10:20
 */
@Slf4j
public class ScheduleRunnable implements Runnable {

    private final Object target;
    private final Method method;
    private final String params;

    /**
    * 业务构造方法.
    * @author pbody
    * @date 4:11 PM 2022/3/29
    * @param beanName  实体名称
    * @param methodName 方法名称
    * @param params 任务参数
    **/
    public ScheduleRunnable(final String beanName, final String methodName, final String params) throws NoSuchMethodException {
        this.target = SpringContextUtils.getBean(beanName);
        this.params = params;

        if (StringUtils.isNotBlank(params)) {
            this.method = target.getClass().getDeclaredMethod(methodName, String.class);
        } else {
            this.method = target.getClass().getDeclaredMethod(methodName);
        }
    }

    @Override
    public void run() {
        try {
            ReflectionUtils.makeAccessible(method);
            if (StringUtils.isNotBlank(params)) {
                method.invoke(target, params);
            } else {
                method.invoke(target);
            }
        } catch (Exception e) {
            log.error("执行定时任务失败", e);
            throw new RException("执行定时任务失败：" + e.getCause().getMessage(), e);
        }
    }
}
